package com.app.art.ability.login;

import com.app.art.utils.jwt.JwtTokenUtil;
import com.atom.module.author.pojo.entity.Author;
import com.atom.module.author.service.AuthorService;
import com.atom.module.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.function.Function;


@Tag(name = "登录相关接口")
@RestController
@RequestMapping("/system")
@Slf4j
public class LoginController {

    @Autowired
    private AuthorService authorService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 登录
     */
    @Operation(summary = "登录")
    @PostMapping("/login")
    public Result<?> login(@RequestBody LoginDTO loginDTO) {
        log.info("员工登录：{} ", loginDTO);
        Author authorByAccount = authorService.getAuthorByAccount(loginDTO.getUsername());
        if (authorByAccount == null) {
            return Result.error("getAuthorByAccount error");
        }
        log.info("员工登录 result ：{} ", authorByAccount.getAccount());
        String accessToken = jwtTokenUtil.generateAccessToken(authorByAccount.getAccount());
        String refreshToken = jwtTokenUtil.generateRefreshToken(authorByAccount.getAccount());
        //登录成功后，生成jwt令牌
        LoginVO employeeLoginVO = LoginVO.builder().id(authorByAccount.getId())
                .username(authorByAccount.getUsername())
                .account(authorByAccount.getAccount())
                .token(accessToken)
                .refresh(refreshToken)
                .build();
        return Result.success(employeeLoginVO);
    }

    /**
     * 登录
     */
    @Operation(summary = "刷新Token")
    @PostMapping("/refresh")
    public Result<?> refreshToken(@RequestBody TokenDTO token) {
        log.info("刷新Token：{} ", token);
        String accessToken = jwtTokenUtil.refreshAccessToken(token.getRefreshToken());
        log.info("刷新Token result ：{} ", accessToken);
        return Result.success(new TokenDTO(accessToken , token.getRefreshToken()));
    }

    /**
     * 登录
     */
    @Operation(summary = "刷新Token")
    @GetMapping("/list")
    public Result<?> list() {
        List<AuthorVO> authors = authorService.listAccount().stream().map(author -> new AuthorVO(author.getUsername() , author.getSex())).toList();
        return Result.success(authors);
    }

}
